from threading import Thread, Lock
from multiprocessing import Process, Lock
from multiprocessing import Queue

# 多进程锁
# 文件
def save_to_file(index, lock):
    # f = open("test.log", "w", encoding="utf-8")
    # f.write(index)
    # f.close()

    # lock.acquire()
    with lock:
        with open("test.log", "a", encoding="utf-8") as f:
            f.write(str(index) + '\n')
    # lock.release()

# 消息队列
def save_to_queue(index, my_queue):
    my_queue.put(index)
    # print(my_queue.get())

if __name__ == "__main__":
    process_array = []
    my_queue = Queue()
    # lock = Lock()
    for i in range(5):
        # p = Process(target=save_to_file, args=(i, lock))
        p = Process(target=save_to_queue, args=(i, my_queue))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    # print("done!")

    while True:
        print(my_queue.get())

# 多线程锁
x = 0
lock = Lock()

def lock_Thread():
    global x
    for i in range (10**6):
        with lock:
            x += 1
            x -= 1

if __name__ == "__main__":
    thread_array = []
    for i in range(2):
        t = Thread(target=lock_Thread)
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    print(x)